<template>
  <el-upload
    class="avatar-uploader"
    action="https://image.zdxblog.cn/upload/uploadFile"
    v-loading="uploadLoading"
    :show-file-list="false"
    :auto-upload="true"
    :before-upload="beforeFileUpload"
    :on-change="handleFileChange"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><UploadFilled /></el-icon>
  </el-upload>
</template>

<script setup lang="ts" name="GcUploadImage">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadRawFile, UploadFile } from 'element-plus'

const props = defineProps({
  imageUrl: {
    type: String
  }
})
const emit = defineEmits(['get-image'])
const uploadLoading = ref(false)
const imageUrl = computed({
  get: () => {
    return props.imageUrl
  },

  set: (val) => {
    emit('get-image', val)
  }
})

function handleFileChange (uploadFile: UploadFile) {
  if (uploadFile.status === 'uploading') {
    uploadLoading.value = true
    return
  }
  if (uploadFile.status === 'success') {
    imageUrl.value = (uploadFile.response as any).data
    uploadLoading.value = false
    return
  }
  if (uploadFile.status === 'fail') {
    ElMessage.error('上传图片失败')
    uploadLoading.value = false
  }
}

function beforeFileUpload (rawFile: UploadRawFile) {
  const re = /^.*?(jpg|gif|png|svg)$/i
  if (!re.test(rawFile.name)) {
    ElMessage.error('只允许上传图片格式的文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}
</script>

<style lang="scss" scoped></style>
